package com.lemon.funplus;

import java.util.ArrayList;

import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.GoogleAuthUtil;
import com.lemon.funplus.parse.CMD;
import com.lemon.funplus.parse.JsonParser;
import com.lemon.funplus.ulti.BaseEngine;

public class AccountRegistrationActivity extends BaseActivity {
	EditText edtPhone, edtPass, edtRepass;
//	, edtName, edtEmail;
	TextView textCaution;
	Button btnRegister, btnLogin;
	String username = "", password = "", fullname = "funplus", email = "@", phone = "", gender = "0";
	AccountManager mAccountManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account_register);
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		menuFragment.ACCOUNT.select();
		myActionBar.setTitle(getResources().getString(R.string.register));
	}

	void initView() {
		edtPhone = (EditText) findViewById(R.id.register_edittext_user);
		edtPass = (EditText) findViewById(R.id.register_edittext_password);
		edtRepass = (EditText) findViewById(R.id.register_edittext_repassword);
		textCaution = (TextView) findViewById(R.id.register_textview_caution);
		btnLogin = (Button) findViewById(R.id.register_button_login);
		btnRegister = (Button) findViewById(R.id.register_button_register);
//		edtName = (EditText) findViewById(R.id.register_edittext_fullname);
//		edtEmail = (EditText) findViewById(R.id.register_edittext_email);
//		edtEmail.setText(getAccountNames()[0]);
		edtRepass.setOnEditorActionListener(new EditText.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					register();
				}
				return false;
			}
		});
		btnRegister.setOnClickListener(clickListener);
		btnLogin.setOnClickListener(clickListener);
	}

	private String[] getAccountNames() {
		mAccountManager = AccountManager.get(AccountRegistrationActivity.this);
		Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
		String[] names = new String[accounts.length];
		for (int i = 0; i < names.length; i++) {
			names[i] = accounts[i].name;
		}
		return names;
	}

	private void register() {
		if (!edtPhone.getText().toString().equals("") && !edtPass.getText().toString().equals("")
				&& !edtRepass.getText().toString().equals("")) {
			if (BaseEngine.checkVinaPhone(edtPhone.getText().toString())) {
				if (edtPass.getText().toString().length() >= 8) {
					if (edtPass.getText().toString().equals(edtRepass.getText().toString())) {
						textCaution.setText("");
						username = edtPhone.getText().toString();
						password = edtPass.getText().toString();
//						fullname = edtName.getText().toString();
						phone = username;
//						if (!edtEmail.getText().toString().equals(""))
//							email = edtEmail.getText().toString();
						new AsyncTaskParseJson().execute("");
					} else
						textCaution.setText("Nhập lại mật khẩu không đúng!");
				} else
					textCaution.setText("Mật khẩu tối thiểu là 8 ký tự!");
			} else
				textCaution.setText(getResources().getString(R.string.phone_error));
		} else
			textCaution.setText("Bạn phải nhập đầy đủ thông tin!");
	}

	OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.register_button_login:
				onBackPressed();
				break;
			case R.id.register_button_register:
				register();
				break;
//			case R.id.register_button_active:
//				Intent intent = new Intent(AccountRegistrationActivity.this, AccountActiveActivity.class);
//				startActivity(intent);
//				break;
			default:
				break;
			}
		}
	};

	public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
		JSONObject jsonObject;
		ProgressDialog progressDialog = new ProgressDialog(AccountRegistrationActivity.this);

		@Override
		protected void onPreExecute() {
			if (!progressDialog.isShowing())
				progressDialog.show();
		}

		@Override
		protected String doInBackground(String... arg0) {
			String str = JsonParser.register(username, password, fullname, email, phone, gender);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			BaseEngine.showLogformLongString("", result);
			if (progressDialog.isShowing())
				progressDialog.hide();
			if (result != null)
				try {
					ArrayList<String> list = JsonParser.readListdata(result);
					Log.e("", "status: " + list.get(0));
					Log.e("", "mss: " + list.get(1));
					if (list != null && list.size() > 1) {
						if (list.get(0).equals(CMD.TAG_SUCCESS)) {
							Toast.makeText(AccountRegistrationActivity.this, list.get(1), Toast.LENGTH_SHORT).show();
							Intent intent = new Intent(AccountRegistrationActivity.this, AccountActiveActivity.class);
							intent.putExtra("phone", phone);
							startActivity(intent);
						} else {
							new AlertDialog.Builder(AccountRegistrationActivity.this).setTitle("Error " + list.get(0)).setMessage(list.get(1))
									.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog, int which) {
										}
									}).setIcon(android.R.drawable.ic_dialog_alert).show();
						}
					} else
						Toast.makeText(AccountRegistrationActivity.this, getResources().getString(R.string.request_error), Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
	}
}
